package com.fjzx.androidframe.global.util;

import android.content.Context;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.text.DecimalFormat;

/**
 * 文件管理类
 *
 * @author xiongyongcong
 */
public class XFile {
    private static final String DIR_LOG = "log";
    private static final String DIR_CACHE = "cache";
    private static final String DIR_TEMP = "temp";
    private static final String DIR_DOWNLOAD = "download";
    private static final String DIR_DB = "db";
    private static final String DIR_MEDIA = "media";
    private static final String DIR_PLUGIN = "plugin";
    private static File appDir;
    private static File logDir;
    private static File tempDir;
    private static File cacheDir;
    private static File downloadDir;
    private static File dbDir;
    private static File mediaDir;
    private static File pluginDir;

    /**
     * 获取应用根目录
     *
     * @return
     */
    public static File getAppDir(Context context) {
        if (appDir == null) {
            appDir = context.getExternalCacheDir().getParentFile();
        }
        if (!appDir.exists()) {
            appDir.mkdirs();
        }
        return appDir;
    }

    /**
     * 获取应用Log目录
     *
     * @return
     */
    public static File getAppLogDir(Context context) {
        if (logDir == null) {
            logDir = new File(getAppDir(context) + File.separator + DIR_LOG);
        }
        if (!logDir.exists()) {
            logDir.mkdirs();
        }
        return logDir;
    }

    /**
     * 获取应用缓存目录
     *
     * @return
     */
    public static File getAppCacheDir(Context context) {
        if (cacheDir == null) {
            cacheDir = new File(getAppDir(context) + File.separator + DIR_CACHE);
        }
        if (!cacheDir.exists()) {
            cacheDir.mkdirs();
        }
        return cacheDir;
    }

    /**
     * 获取应用下载目录
     *
     * @param context
     * @return
     */
    public static File getAppDownloadDir(Context context) {
        if (downloadDir == null) {
            downloadDir = new File(getAppDir(context) + File.separator + DIR_DOWNLOAD);
        }
        if (!downloadDir.exists()) {
            downloadDir.mkdirs();
        }
        return downloadDir;
    }

    /**
     * 获取应用临时文件目录
     *
     * @return
     */
    public static File getAppTempDir(Context context) {
        if (tempDir == null) {
            tempDir = new File(getAppDir(context) + File.separator + DIR_TEMP);
        }
        if (!tempDir.exists()) {
            tempDir.mkdirs();
        }
        return tempDir;
    }

    /**
     * 获取应用数据库文件夹
     *
     * @param context
     * @return
     */
    public static File getAppDbDir(Context context) {
        if (dbDir == null) {
            dbDir = new File(getAppDir(context) + File.separator + DIR_DB);
        }
        if (!dbDir.exists()) {
            dbDir.mkdirs();
        }
        return dbDir;
    }

    /**
     * 获取媒体文件（图片、音视频等）文件夹目录
     *
     * @param context
     * @return
     */
    public static File getAppMediaDir(Context context) {
        if (mediaDir == null) {
            mediaDir = new File(getAppDir(context) + File.separator + DIR_MEDIA);
        }
        if (!mediaDir.exists()) {
            mediaDir.mkdirs();
        }
        return mediaDir;
    }

    /**
     * 获取插件文件夹目录
     *
     * @param context
     * @return
     */
    public static File getAppPluginDir(Context context) {
        if (pluginDir == null) {
            pluginDir = new File(getAppDir(context) + File.separator + DIR_PLUGIN);
        }
        if (!pluginDir.exists()) {
            pluginDir.mkdirs();
        }
        return pluginDir;
    }

    /**
     * 文件复制
     *
     * @param s
     * @param t
     */
    public static void fileChannelCopy(File s, File t) {
        FileInputStream fi = null;
        FileOutputStream fo = null;
        try {
            fi = new FileInputStream(s);
            fo = new FileOutputStream(t);
            FileChannel in = fi.getChannel();
            FileChannel out = fo.getChannel();
            in.transferTo(0, in.size(), out);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fo != null) {
                    fo.close();
                }
                if (fi != null) {
                    fi.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * @param fileLen
     * @return String
     * @throws
     * @Title: formatFileSizeToString
     * @Description: TODO(文件大小转换)
     * @CreateBy: 陈权
     * @CreateTime: 2018年7月20日 下午2:15:06
     * @UpdateBy: 陈权
     * @UpdateTime: 2018年7月20日 下午2:15:06
     */
    public static String formatFileSizeToString(long fileLen) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileLen < 1024) {
            fileSizeString = df.format((double) fileLen) + "B";
        } else if (fileLen < 1048576) {
            fileSizeString = df.format((double) fileLen / 1024) + "K";
        } else if (fileLen < 1073741824) {
            fileSizeString = df.format((double) fileLen / 1048576) + "M";
        } else {
            fileSizeString = df.format((double) fileLen / 1073741824) + "G";
        }
        return fileSizeString;
    }

    /**
     * 删除文件
     */
    public static boolean deleteFile(File file) throws IOException {
        return file != null && file.delete();
    }

    /**
     * 获取文件扩展名
     *
     * @param filename
     * @return 返回文件扩展名
     */
    public static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }

    /**
     * 读取指定文件的输出
     */
    public static String getFileOutputString(String path) {
        try {
            BufferedReader bufferedReader = new BufferedReader(new FileReader(path), 8192);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                sb.append("\n").append(line);
            }
            bufferedReader.close();
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
